import {
  request
} from '../../request/index'
import regeneratorRuntime, { async } from '../../lib/runtime/runtime'
import PubSub from 'pubsub-js'

// pages/searchList/index.js
Page({

  data: {
    keyword:"",
    musicList:[],
    index:0
  },

  onLoad: function (options) {
    let keyword = options.name
    this.getMusicList(keyword)

        //订阅来自详情页的发布消息
        PubSub.subscribe('switchType',(msg,type)=>{
          let {musicList , index} = this.data
          if(type === 'pre'){ //上一首
            (index === 0) && (index = musicList.length)
            index -= 1
          }
          else if(type === 'loop'){ // 循环播放
            index = index
          }
          
          else{ //  下一首
            (index === musicList.length-1) && (index = -1)
            index += 1
          }
    
          this.setData({
            index
          })
          let musicId = musicList[index].id
    
          //发布消息
          PubSub.publish("musicId",musicId)
    
        })

  },

  //获取歌曲列表
  async getMusicList(keyword){
    let res = await request({url:"search",data:{keywords:keyword,limit:100}})
    this.setData({
      musicList:res.data.result.songs
    })

  },

  toDetail(e){
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index

    this.setData({
      index
    })
    wx.navigateTo({
      url: '/pages/songDetail/index?id=' + id
    });
  }


})